多層的繼承(Hierarchical Inheritance)
子類別繼承父類別後,那個子類別可以再當父類別,供其他的子類別繼承,形成多層的繼承關係,最下層的子類別,會繼承到上面所有父類別的成員變數及方法。
package com.mycompany.testseven;
public class Shape {
protected double x,y;
public Shape(double x,double y){
this.x=x;
this.y=y;
}
public String toString(){
return "原點:("+x+", "+y+")";
}
}
package com.mycompany.testseven;
public class Circle extends Shape{
protected double r;
protected final double PI=3.14;
public Circle(double x,double y,double r){
super(x,y);
this.r=r;
}
public String toString(){
return super.toString()+", 半徑:"+r;
}
public double area(){
return (r*r*PI);
}
}
package com.mycompany.testseven;
public class Cylinder extends Circle{
protected double h;
public Cylinder(double x,double y,double r,double h){
super(x,y,r);
this.h=h;
}
public String toString(){
return super.toString()+", 高:"+h;
}
public double area(){
return (r*r*PI*h);
}
}
package com.mycompany.testseven;
public class Rectangle extends Shape{
protected double w,h;
public Rectangle(double x,double y,double w,double h){
super(x,y);
this.w=w;
this.h=h;
}
public String toString(){
return super.toString()+", 長:"+w+", 寬:"+h;
}
public double area(){
return (w*h);
}
}
package com.mycompany.testseven;
public class testSeven {
public static void main(String[] args) {
Shape s=new Shape(1,2);
Rectangle re= new Rectangle(3,4,7,9);
Circle ci=new Circle(3,4,10);
Cylinder cr=new Cylinder(3,4,10,3);
System.out.println("Rectangle"+re.toString());
System.out.println("長方形面積:"+re.area());
System.out.println("Circle"+ci.toString());
System.out.println("圓形面積:"+ci.area());
System.out.println("Cylinder"+cr.toString());
System.out.println("圓柱體面積:"+cr.area());
}
}
Cylinder繼承Circle,Circle和Rectangle繼承Shape,所以Cylinder也能呼叫Shape的成員變數及方法。
方法的重新定義
如果父類別中定義的方法內容不適用於子類別,可在子類別中重新定義(Overriding)方法。
多形(Polymorphism)
因為下層類別包含上層的成員,所以可以使用上層類別的參照指向下層物件。
多形的規則:
package com.mycompany.testeight;
class Land{
double area(){
return 0;
}
}
class Circle extends Land{
int r;
Circle(int r){
this.r=r;
}
double area(){
return 3.14*r*r;
}
}
class Rectangle extends Land{
int x,y;
Rectangle(int x,int y){
this.x=x;
this.y=y;
}
double area(){
return x*y;
}
}
class Calculator{
double price;
Calculator(double price){
this.price=price;
}
double calculatePrice(Land l){
return l.area()*price;
}
}
public class testEight {
public static void main(String[] args) {
Rectangle re= new Rectangle(7,9);
Circle ci=new Circle(2);
Calculator price=new Calculator(2000.0);
System.out.println("圓形ci土地:"+price.calculatePrice(ci)+"元");
System.out.println("長方形re土地:"+price.calculatePrice(re)+"元");
}
}
使用多形,讓不同形狀的土地類別繼承同一父類別Land,在執行時,依據指向的物件呼叫對應的area(),當有新的土地類別要計算價錢時,不需要修改Calculator類別,讓程式更有彈性。
參考資料:
最新java程式語言第六版